from flask import Flask, request, jsonify
app = Flask(__name__)
import pandas as pd
from itertools import combinations

# 加载模型
frequent_itemsets = pd.read_pickle('frequent_itemsets.pkl')
rules = pd.read_pickle('rule.pkl')


@app.route('/recommend', methods=['POST'])
def recommend():
    data = request.json.get('items', [])
    
    # 生成关联规则的推荐
    recommendations = []
    for idx, rule in rules.iterrows():
        antecedents = list(rule['antecedents'])
        consequents = list(rule['consequents'])
        
        # 检查输入的物品是否满足前提条件
        if set(antecedents).issubset(set(data)):
            recommendations.extend(consequents)

    # 去重并排除已购买物品
    recommendations = list(set(recommendations) - set(data))
    
    return jsonify({'recommendations': recommendations})

if __name__ == '__main__':
    app.run()
